package com.cpecc.dao.system;

import com.cpecc.model.system.Dep;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository
public class DepDao {

	@Resource
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Dep getRoot(){
		String hql="from Dep t where t.parent=null";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		if(query.list().size()>0) {
			return (Dep) query.list().get(0);
		}
		return null;
	}
	
	public int getChildSize(String pId){
		String hql="from Dep t where t.parent.id=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, pId);
		return query.list().size();
	}
	
	public boolean getByDaiMa(String daiMa){
		String hql="from Dep t where t.daiMa=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, daiMa);
		return query.list().size()>0;
	}
	
	public Dep get(String id){
		return (Dep) sessionFactory.getCurrentSession().get(Dep.class, id);
	}
	
	public boolean cover(Dep dep){
		Session session=sessionFactory.getCurrentSession();
		String hql="update Dep t set t.depName=?,t.description=?,t.parent=?,t.role=?,t.cengJi=?,t.daiMa=? where t.id=?";
		Query query=session.createQuery(hql);
		query.setString(0, dep.getDepName());
		query.setString(1, dep.getDescription());
		query.setParameter(2, dep.getParent());
		query.setParameter(3, dep.getRole());
		query.setInteger(4, dep.getCengJi());
		query.setString(5, dep.getDaiMa());
		query.setString(6, dep.getId());
		return (query.executeUpdate()>0);
	}
	
	public void save(Dep dep){
		Session session=sessionFactory.getCurrentSession();
		session.save(dep);
		session.flush();
	}
	
	public boolean hasChild(Dep dep){
		String hql="from Dep t where t.parent.id=?";
		Query query=sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, dep.getId());
		return query.list().size()>0;
	}
	
	public void delete(Dep dep){
		Session session=sessionFactory.getCurrentSession();
		session.delete(dep);
		session.flush();
	}
	
	public Dep getDep(String id){
		Session session=sessionFactory.openSession();
		Dep dep=(Dep) session.get(Dep.class, id);
		session.close();
		return dep;
	}
}
